import { apiClient } from '@/lib/api-client';
import type { 
  LoginRequest, 
  RegisterRequest, 
  AuthResponse, 
  ApiResponse,
  User 
} from '@/lib/types/api';

interface JwtPayload {
  userId: string;
  email: string;
  exp?: number;
  iat?: number;
}

export class AuthService {
  static async login(credentials: LoginRequest): Promise<ApiResponse<AuthResponse>> {
    const response = await apiClient<LoginRequest, AuthResponse>('/auth/login', {
      method: 'POST',
      body: credentials,
    });

    if (response.status && response.data?.token) {
      localStorage.setItem('token', response.data.token);
      localStorage.setItem('user', JSON.stringify(response.data.user));
    }

    return response;
  }

  static async register(data: RegisterRequest): Promise<ApiResponse<AuthResponse>> {
    try {
      const response = await apiClient<RegisterRequest, AuthResponse>('/auth/register', {
        method: 'POST',
        body: data,
      });

      if (response.status && response.data) {
        if (response.data.token && response.data.user) {
          localStorage.setItem('token', response.data.token);
          localStorage.setItem('user', JSON.stringify(response.data.user));
        }
      }

      return response;
    } catch (error) {
      console.error('Registration error:', error);
      return {
        status: false,
        message: error instanceof Error ? error.message : '注册失败',
      };
    }
  }

  static async logout(): Promise<void> {
    try {
      await apiClient('/auth/logout', { method: 'POST' });
    } finally {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    }
  }

  static async getCurrentUser(): Promise<ApiResponse<User>> {
    return await apiClient<null, User>('/auth/me', {
      method: 'GET',
    });
  }

  static getToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('token');
  }

  static getUser(): User | null {
    if (typeof window === 'undefined') return null;
    const user = localStorage.getItem('user');
    return user ? JSON.parse(user) : null;
  }

  static isAuthenticated(): boolean {
    const token = this.getToken();
    if (!token) return false;

    try {
      // 检查 token 是否过期
      const user = this.getUser();
      return !!user;
    } catch {
      return false;
    }
  }

  static async updateUser(data: Partial<User>): Promise<ApiResponse<User>> {
    return await apiClient<Partial<User>, User>('/auth/me', {
      method: 'PUT',
      body: data,
    });
  }

  static async deleteUser(): Promise<ApiResponse<void>> {
    return await apiClient<null, void>('/auth/me', {
      method: 'DELETE',
    });
  }
} 